package com.sfj.system.service.userinfo;

import com.kaka.starter.token.service.TokenService;
import com.sfj.common.exception.CheckException;
import com.sfj.system.dto.LoginDTO;
import com.sfj.system.dto.LoginResDTO;
import com.sfj.system.dto.group.GroupTreeDTO;
import com.sfj.system.dto.role.RoleInfoRes;
import com.sfj.system.dto.userinfo.UserInfoAddDTO;
import com.sfj.system.dto.userinfo.UserInfoImportDTO;
import com.sfj.system.dto.userinfo.UserInfoUpdDTO;
import com.sfj.system.entity.UserInfoEntity;
import com.sfj.system.enums.DeptEnum;
import com.sfj.system.exception.LoginException;
import com.sfj.system.mapper.UserInfoMapper;
import com.sfj.system.service.group.GroupService;
import com.sfj.system.service.jiekou.TongyiUserInfo;
import com.sfj.system.service.role.RoleInfoService;
import com.sfj.system.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kaka
 * @date 2020-09-24
 */
@Slf4j
@Service
public class UserInfoService {

    @Resource
    private UserInfoMapper userinfoMapper;

    @Autowired
    private UserInfoQueryService userinfoQueryService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RoleInfoService roleInfoService;
    @Autowired
    private GroupService groupService;

    @Transactional
    public void save(UserInfoAddDTO record) {
        //验证警号重复
        UserInfoEntity infoEntity = userinfoQueryService.selectByPoliceNum(record.getPoliceNum());
        if (infoEntity != null) {
            throw new CheckException("该警号已存在！");
        }
        UserInfoEntity userinfoEntity = new UserInfoEntity();
        BeanUtils.copyProperties(record, userinfoEntity);
        userinfoEntity.setCreateTime(LocalDateTime.now().withNano(0));
        userinfoEntity.setUpdateTime(LocalDateTime.now().withNano(0));
        userinfoMapper.insertSelective(userinfoEntity);
    }


    @Transactional
    public void upd(UserInfoUpdDTO record) {
        //验证警号重复
        validUserByPoliceNum(record.getPoliceNum(), record.getUserId());

        UserInfoEntity infoEntity = userinfoQueryService.selectByPoliceNum(record.getPoliceNum());
        if (infoEntity != null && infoEntity.getUserId() != record.getUserId()) {
            throw new CheckException("该警号已存在！");
        }

        UserInfoEntity userinfoUpd = new UserInfoEntity();
        BeanUtils.copyProperties(record, userinfoUpd);

        userinfoUpd.setUpdateTime(LocalDateTime.now().withNano(0));
        userinfoMapper.updateSelective(userinfoUpd);
    }

    @Transactional
    public void del(Integer id) {
        UserInfoEntity userinfoEntity = userinfoQueryService.getById(id);
        if (userinfoEntity == null) {
            throw new CheckException("用户信息不存在");
        } else if ("admin".equals(userinfoEntity.getName())) {
            throw new CheckException("默认用户无法删除");
        }
        userinfoMapper.deleteByPrimaryKey(id);
    }

    /**
     * 用户登录
     */
    public Map<String, Object> login(TongyiUserInfo tongyiUserInfo) {

        LoginResDTO loginResDTO = userinfoQueryService.selectByUserName(tongyiUserInfo.getUserName());
        if (loginResDTO == null) {
            throw new LoginException("用户名不存在");
        }

        if (tongyiUserInfo.getLoginName().equals(loginResDTO.getPoliceNum())) {
            // 查询用户权限菜单
            Map<String, Object> resultMap = getTokenMap(loginResDTO);
            return resultMap;
        } else {
            throw new LoginException("用户不存在");
        }
    }

    /**
     * 用户登录返回
     *
     * @param infoEntity
     * @return
     */
    private Map<String, Object> getTokenMap(LoginResDTO infoEntity) {
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("userName", infoEntity.getName());
        tokenMap.put("userId", infoEntity.getUserId());
        tokenMap.put("groupId", infoEntity.getGroup());
        tokenMap.put("groupName", infoEntity.getGroupName());
        tokenMap.put("roleId", infoEntity.getRole());
        tokenMap.put("level", infoEntity.getRoleLevel());


        tokenService.destory(infoEntity.getUserId());
        // 生成token
        tokenService.set(infoEntity.getUserId(), tokenMap);
        tokenMap.put("token", tokenService.get(infoEntity.getUserId()).getToken());

        return tokenMap;
    }

    public void validUserByPoliceNum(String policeNum, Integer userId) {
        UserInfoEntity infoEntity = userinfoQueryService.selectByPoliceNum(policeNum);
        if (infoEntity != null && infoEntity.getUserId() != userId) {
            throw new CheckException("该警号已存在！");
        }
    }

    @Transactional
    public String importFromExcel(MultipartFile file) throws Exception {
        // 1. 解析 Excel 数据
        List<UserInfoImportDTO> userList = FileUtil.parseXlsx(file.getInputStream());
        if (userList.isEmpty()) throw new CheckException("解析文件失败");

        // 2. 初始化中文转 ID 映射字典

        // 2.1 Dept（来自 DeptEnum）
        Map<String, Integer> deptNameToIdMap = Arrays.stream(DeptEnum.values())
                .collect(Collectors.toMap(DeptEnum::getName, DeptEnum::getId));

        // 2.2 Role（来自数据库）
        List<RoleInfoRes> roleList = roleInfoService.queryRoleList();
        Map<String, Integer> roleNameToIdMap = roleList.stream()
                .collect(Collectors.toMap(RoleInfoRes::getRoleName, RoleInfoRes::getRoleId));

        // 2.3 Group（来自数据库）
        List<GroupTreeDTO> groupList = groupService.queryGroupList();
        Map<String, Integer> groupNameToIdMap = groupList.stream()
                .collect(Collectors.toMap(GroupTreeDTO::getGroupName, GroupTreeDTO::getGroupId));

        // 3. 构造 Entity 列表
        List<UserInfoEntity> entityList = new ArrayList<>();
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);
        for (UserInfoImportDTO dto : userList) {
            UserInfoEntity entity = new UserInfoEntity();

            entity.setUserId(dto.getUserId());
            entity.setName(dto.getName());
            entity.setIphone(dto.getIphone());
            entity.setPoliceNum(dto.getPoliceNum());

            Integer tmp = 99;//未知  (导入没填对)
            entity.setRole(roleNameToIdMap.getOrDefault(dto.getRole(), tmp));
            entity.setGroup(groupNameToIdMap.getOrDefault(dto.getGroup(), tmp));
            entity.setDept(deptNameToIdMap.getOrDefault(dto.getDept(), tmp));

            entity.setCreateTime(localDateTime);
            entity.setUpdateTime(localDateTime);

            // 验证警号是否重复 重复舍弃
            UserInfoEntity infoEntity = userinfoQueryService.selectByPoliceNum(entity.getPoliceNum());
            if (infoEntity == null) {
                entityList.add(entity);
            }

        }

        // 4. 执行批量插入
        if (!entityList.isEmpty()) {
            userinfoMapper.insertBatch(entityList);
        }
        int removeCount = entityList.size();
        if (removeCount == 0) {
            return "失败";
        } else if (userList.size() == removeCount) {
            return "成功导入" + userList.size() + "条数据";
        } else {
            return "共导入" + removeCount + "条数据！成功" + (userList.size() - removeCount) + "条数据";
        }
    }

}